import { getTabJsonModelFromLocal, setTabJsonModelToLocal } from '@renderer/store/localstorage'
import { onMounted, ref } from 'vue'
import { tabJsonModelAtom, tabModelAtom } from '@renderer/store/jotai'

import { WELCOME_TAB_ITEM } from '@renderer/utils/constant'
// import {
//   DockLocation,
//   Actions
// } from 'flexlayout-react'
import { fileTreeIndexeddbStorage } from '@renderer/store/fileTreeIndexeddb'
import { useAtom } from 'jotai-vue'
import useCurrentFile from '../useCurrentFile'

export default function useTabJsonModel() {
  const [tabJsonModel, setTabJsonModel] = useAtom(tabJsonModelAtom)
  const [model] = useAtom(tabModelAtom)
  const { updateCurrentFile } = useCurrentFile()

  onMounted(() => {
    const tabJsonModelFromLocal = getTabJsonModelFromLocal()
    setTabJsonModel(tabJsonModelFromLocal)
  })

  const getTabList = (json, tabList = []) => {
    if (json.type === 'tab') {
      tabList.push(json)
    } else {
      json.children?.forEach((child) => {
        getTabList(child, tabList)
      })
    }
    return tabList
  }

  const getActiveTabset = (tabJsonModel) => {
    const layoutChildren = tabJsonModel.layout.children
    let activeTabset = layoutChildren[0]

    for (const child of layoutChildren) {
      if (child.active) {
        activeTabset = child
        break
      }
    }

    return activeTabset
  }

  const getSelectedTab = (tabJsonModel) => {
    const layoutChildren = tabJsonModel.layout.children
    let selectedTab = layoutChildren[0].children[0]

    for (const child of layoutChildren) {
      if (child.active) {
        selectedTab = child.children[child.selected || 0]
        break
      }
    }

    return selectedTab
  }

  const updateTabJsonModelWhenCurrentFileChanged = async (currentFile, tabModel) => {
    if (!currentFile || !tabModel) return

    const tabJsonModel = tabModel.toJson()
    const tabList = getTabList(tabJsonModel.layout)
    const _tabIndex = tabList.findIndex((tab) => tab.id === currentFile.id)

    if (_tabIndex < 0) {
      addTab(currentFile, tabModel)
      const newTabJsonModel = tabModel.toJson()
      setTabJsonModel(newTabJsonModel)
      setTabJsonModelToLocal(JSON.stringify(newTabJsonModel))
    } else {
      // tabModel.doAction(Actions.selectTab(currentFile.id))
    }
  }

  const addTab = (currentFile, model) => {
    if (!model) return

    const newTabItem = {
      id: currentFile.id,
      name: currentFile.name,
      type: 'tab',
      config: currentFile
    }

    const json = model.toJson()
    const activeTabset = getActiveTabset(json)

    // model.doAction(Actions.addNode(newTabItem, activeTabset.id || '', DockLocation.CENTER, 0, true))
  }

  const switchToWelcomePage = () => {
    if (!model) return

    const json = model.toJson()
    const tabList = json && getTabList(json.layout)
    const welcomeTab = tabList?.find((tab) => tab.config.type === 'welcome')

    if (welcomeTab?.id) {
      // model.doAction(Actions.selectTab(welcomeTab.id))
    } else {
      addTab(WELCOME_TAB_ITEM.config, model)
    }
  }

  const deleteTab = async (fileId, model) => {
    if (!model) return

    // model.doAction(Actions.deleteTab(fileId))
    const newTabJsonModel = model.toJson()
    setTabJsonModel(newTabJsonModel)
    setTabJsonModelToLocal(JSON.stringify(newTabJsonModel))

    const selectedTab = getSelectedTab(newTabJsonModel)
    const currentFile = selectedTab?.id
      ? await fileTreeIndexeddbStorage.getFile(selectedTab.id)
      : undefined
    updateCurrentFile(currentFile)
  }

  const renameTabName = (fileId, name, model) => {
    if (!model) return

    // model.doAction(Actions.renameTab(fileId, name))
    const newTabJsonModel = model.toJson()
    setTabJsonModel(newTabJsonModel)
    setTabJsonModelToLocal(JSON.stringify(newTabJsonModel))
  }

  return {
    tabJsonModel: ref(tabJsonModel.value),
    model: ref(model.value),
    addTab,
    switchToWelcomePage,
    updateTabJsonModelWhenCurrentFileChanged,
    setTabJsonModel,
    deleteTab,
    renameTabName,
    getTabList
  }
}
